﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security;
using System.IO;
using System.Security.Cryptography;
using System.Reflection;
using System.Drawing;
using System.Drawing.Printing;


namespace WebCarLine.Common
{
    public class StringHelp
    {

        public  static string Encrypt(string encryptString, string key, string iv)
        {
            var des=DES.Create();
            byte[] sor = Encoding.UTF8.GetBytes(encryptString);
            //传入key iv
            des.Key = UTF8Encoding.UTF8.GetBytes(key);
            des.IV = UTF8Encoding.UTF8.GetBytes(iv);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
            cs.Write(sor, 0, sor.Length);
            cs.FlushFinalBlock();
            StringBuilder sb = new StringBuilder();

            foreach (byte b in ms.ToArray())
            {
                sb.AppendFormat("{0:X2}", b);
            }

            return sb.ToString();
        }

        public  static string Decrypt(string decryptString, string key, string iv)
        {
            var des =DES.Create();
            byte[] inputByteArray = new byte[decryptString.Length / 2];

            for (int x = 0; x < decryptString.Length / 2; x++)
            {
                int i = (Convert.ToInt32(decryptString.Substring(x * 2, 2), 16));
                inputByteArray[x] = (byte)i;
            }

            //key与加密时的Key保持一致
            des.Key = UTF8Encoding.UTF8.GetBytes(key);
            //skey与加密时的IV保持一致
            des.IV = UTF8Encoding.UTF8.GetBytes(iv);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            StringBuilder ret = new StringBuilder();
            return Encoding.UTF8.GetString(ms.ToArray());
        }

        /// <summary>
        /// 获取位流水号 0001-9999
        /// </summary>
        /// <param name="num">数字</param>
        /// <returns></returns>
        public static string GetIdentityId(int num)
        {
            string tempId = string.Empty;
            for (int i = 1; i <= num; i++)
            {

                if (i < 10)
                {
                    tempId = "0000" + i.ToString().Trim();
                }
                else if (i < 100 && i >= 10)
                {
                    tempId = "000" + i.ToString().Trim();
                }
                else if (i < 999 && i >= 100)
                {
                    tempId = "00" + i.ToString().Trim();
                }
                else if (i <= 9999 && i >= 1000)
                {
                    tempId = "0" + i.ToString().Trim();
                }
                else if (i <= 99999)
                {
                    tempId = i.ToString().Trim();
                }
            }
            return tempId;
        }
        /// <summary>
        /// 返回星期
        /// </summary>
        /// <returns></returns>
        public static string GetDateNowWeekNmae()
        {
            return System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetDayName(DateTime.Now.DayOfWeek);
        }

        public static string GetWeekName()
        {
            return System.DateTime.Today.ToString("dddd", new System.Globalization.CultureInfo("zh-CN"));

        }

        /// <summary> 
        /// Base64加密 
        /// </summary> 
        /// <param name="codeName">加密采用的编码方式</param> 
        /// <param name="source">待加密的明文</param> 
        /// <returns></returns> 

        public static string EncodeBase64(Encoding encode, string source)
        {
            string enString = "";
            byte[] bytes = encode.GetBytes(source);
            try
            {
                enString = Convert.ToBase64String(bytes);
            }
            catch
            {
                enString = source;
            }
            return enString;
        }



        /// <summary> 
        /// Base64解密 
        /// </summary> 
        /// <param name="codeName">解密采用的编码方式，注意和加密时采用的方式一致</param> 
        /// <param name="result">待解密的密文</param> 
        /// <returns>解密后的字符串</returns> 

        public static string DecodeBase64(Encoding encode, string result)
        {
            string decode ;
            byte[] bytes = Convert.FromBase64String(result);
            try
            {
                decode = encode.GetString(bytes);
            }
            catch
            {
                decode = result;
            }
            return decode;
        }


        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="Text">需要加密的字符</param>
        /// <param name="sKey">加密时使用的字符</param>
        /// <returns></returns>
        public static string Encrypt(string  inputText, string sKey)
        {
            var dESCryptoServiceProvider =DES.Create();
            byte[] bytes = Encoding.Default.GetBytes(inputText);
            dESCryptoServiceProvider.Key = Encoding.ASCII.GetBytes(MD5Encode(sKey).Substring(0, 8));
            dESCryptoServiceProvider.IV = Encoding.ASCII.GetBytes(MD5Encode(sKey).Substring(0, 8));
            MemoryStream expr_5B = new MemoryStream();
            CryptoStream expr_68 = new CryptoStream(expr_5B, dESCryptoServiceProvider.CreateEncryptor(), CryptoStreamMode.Write);
            expr_68.Write(bytes, 0, bytes.Length);
            expr_68.FlushFinalBlock();
            StringBuilder stringBuilder = new StringBuilder();
            byte[] array = expr_5B.ToArray();
            for (int i = 0; i < array.Length; i++)
            {
                byte b = array[i];
                stringBuilder.AppendFormat("{0:X2}", b);
            }
            return stringBuilder.ToString();
        }



        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="Text">加密后的字符</param>
        /// <param name="sKey">加密时使用的字符</param>
        /// <returns></returns>
        public static string Decrypt(string inputText, string sKey)
        {
            var dESCryptoServiceProvider = DES.Create();
            int num = inputText.Length / 2;
            byte[] array = new byte[num];
            for (int i = 0; i < num; i++)
            {
                int num2 = Convert.ToInt32(inputText.Substring(i * 2, 2), 16);
                array[i] = (byte)num2;
            }
            dESCryptoServiceProvider.Key = Encoding.ASCII.GetBytes(MD5Encode(sKey).Substring(0, 8));
            dESCryptoServiceProvider.IV = Encoding.ASCII.GetBytes(MD5Encode(sKey).Substring(0, 8));
            MemoryStream memoryStream = new MemoryStream();
            CryptoStream expr_94 = new CryptoStream(memoryStream, dESCryptoServiceProvider.CreateDecryptor(), CryptoStreamMode.Write);
            expr_94.Write(array, 0, array.Length);
            expr_94.FlushFinalBlock();
            return Encoding.Default.GetString(memoryStream.ToArray());
        }


        /// <summary>
        /// 加密时使用的字符MD5处理
        /// </summary>
        /// <param name="strKey">加密时使用的字符</param>
        /// <returns></returns>
        public static String MD5Encode(string strKey)
        {
            byte[] byteList = Encoding.Default.GetBytes(strKey);
            byteList =MD5.Create().ComputeHash(byteList);
            string returnValue = string.Empty;
            for (int i = 0; i < byteList.Length; i++)
            {
                returnValue += byteList[i].ToString("X").PadLeft(2, '0');
            }
            return returnValue;
        }

        #region   数字转大写  
        /// <summary>
        /// 数字转大写
        /// </summary>
        /// <param name="num">数字</param>
        /// <returns></returns>
        public static string CmycurD(decimal num)
        {
            string str1 = "零壹贰叁肆伍陆柒捌玖";            //0-9所对应的汉字 
            string str2 = "万仟佰拾亿仟佰拾万仟佰拾元角分"; //数字位所对应的汉字 
            string str3 = "";    //从原num值中取出的值 
            string str4 = "";    //数字的字符串形式 
            string str5 = "";  //人民币大写金额形式 
            int i;    //循环变量 
            int j;    //num的值乘以100的字符串长度 
            string ch1 = "";    //数字的汉语读法 
            string ch2 = "";    //数字位的汉字读法 
            int nzero = 0;  //用来计算连续的零值是几个 
            int temp;            //从原num值中取出的值
            num = Math.Round(Math.Abs(num), 2);    //将num取绝对值并四舍五入取2位小数 
            str4 = ((long)(num * 100)).ToString();        //将num乘100并转换成字符串形式 
            j = str4.Length;      //找出最高位 
            if (j > 15) { return "溢出"; }
            str2 = str2.Substring(15 - j);   //取出对应位数的str2的值。如：200.55,j为5所以str2=佰拾元角分
            //循环取出每一位需要转换的值 
            for (i = 0; i < j; i++)
            {
                str3 = str4.Substring(i, 1);          //取出需转换的某一位的值 
                temp = Convert.ToInt32(str3);      //转换为数字 
                if (i != (j - 3) && i != (j - 7) && i != (j - 11) && i != (j - 15))
                {
                    //当所取位数不为元、万、亿、万亿上的数字时 
                    if (str3 == "0")
                    {
                        ch1 = "";
                        ch2 = "";
                        nzero = nzero + 1;
                    }
                    else
                    {
                        if (str3 != "0" && nzero != 0)
                        {
                            ch1 = "零" + str1.Substring(temp * 1, 1);
                            ch2 = str2.Substring(i, 1);
                            nzero = 0;
                        }
                        else
                        {
                            ch1 = str1.Substring(temp * 1, 1);
                            ch2 = str2.Substring(i, 1);
                            nzero = 0;
                        }
                    }
                }
                else
                {
                    //该位是万亿，亿，万，元位等关键位 
                    if (str3 != "0" && nzero != 0)
                    {
                        ch1 = "零" + str1.Substring(temp * 1, 1);
                        ch2 = str2.Substring(i, 1);
                        nzero = 0;
                    }
                    else
                    {
                        if (str3 != "0" && nzero == 0)
                        {
                            ch1 = str1.Substring(temp * 1, 1);
                            ch2 = str2.Substring(i, 1);
                            nzero = 0;
                        }
                        else
                        {
                            if (str3 == "0" && nzero >= 3)
                            {
                                ch1 = "";
                                ch2 = "";
                                nzero = nzero + 1;
                            }
                            else
                            {
                                if (j >= 11)
                                {
                                    ch1 = "";
                                    nzero = nzero + 1;
                                }
                                else
                                {
                                    ch1 = "";
                                    ch2 = str2.Substring(i, 1);
                                    nzero = nzero + 1;
                                }
                            }
                        }
                    }
                }
                if (i == (j - 11) || i == (j - 3))
                {
                    //如果该位是亿位或元位，则必须写上 
                    ch2 = str2.Substring(i, 1);
                }
                str5 = str5 + ch1 + ch2;
                if (i == j - 1 && str3 == "0")
                {
                    //最后一位（分）为0时，加上“整” 
                    str5 = str5 + '整';
                }
            }
            if (num == 0)
            {
                str5 = "零元整";
            }
            return str5;
        }



        public static string CmycurD(string numstr)
        {
            try
            {
                decimal num = Convert.ToDecimal(numstr);
                return CmycurD(num);
            }
            catch
            {
                return "非数字形式！";
            }
        }
        #endregion

        /// <summary>
        /// 截取指定小数位
        /// </summary>
        /// <param name="num">数字</param>
        /// <param name="scale">保留的小数位</param>
        /// <returns></returns>
        public static string DecimalToString(decimal num, int scale)
        {
            string numToString = num.ToString();
            int index = numToString.IndexOf(".");
            int length = numToString.Length;

            if (index != -1)
            {
                return string.Format("{0}.{1}",
                    numToString.Substring(0, index),
                    numToString.Substring(index + 1, Math.Min(length - index - 1, scale)));
            }
            else
            {
                return num.ToString();
            }
        }


        //调用DLL  Invoke
        public static void   UseDllList(string spaceName, string dllName)
        {
            //加载程序集(dll文件地址)，使用Assembly类   
            Assembly assembly = Assembly.LoadFile(AppDomain.CurrentDomain.BaseDirectory + dllName);
            //获取类型，参数（名称空间+类）   
            Type type = assembly.GetType(spaceName);
            //创建该对象的实例，object类型，参数（名称空间+类）   
            object instance = assembly.CreateInstance(spaceName);
            //设置ClassLibrary1.dll中Show_Str方法中的参数类型，Type[]类型；如有多个参数可以追加多个   
            Type[] params_type = new Type[1];
            params_type[0] = Type.GetType("System.String");//System.Int32是整型
            //设置ClassLibrary1.dll中Show_Str方法中的参数值；如有多个参数可以追加多个   
            Object[] params_obj = new Object[1];
            params_obj[0] = "lqwvje-Dll里面方法参数";
            //执行Show_Str方法   params_type方法的参数类型   instance对象实例 params_obj参数值
            object value = type.GetMethod("Show_Str", params_type).Invoke(instance, params_obj);
        }

    
        /// <summary>
        /// 32位MD5加密
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private static string Md5Hash(string input)
        {
            var md5Hasher = MD5.Create();
            byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));
            StringBuilder sBuilder = new StringBuilder();
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }
            return sBuilder.ToString();
        }


        /// <summary>
        /// 随机生产自定义长度的字符串
        /// </summary>
        /// <param name="length">字符串长度</param>
        /// <returns>生成的字符串</returns>
        public static string GenerateRandomString(int length)
        {
            const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
            var random = new Random();
            var stringBuilder = new StringBuilder(length);

            for (int i = 0; i < length; i++)
            {
                stringBuilder.Append(chars[random.Next(chars.Length)]);
            }

            return stringBuilder.ToString();
        }
    }
}
